package mt.omid.dimomuth.statistics;


import java.io.IOException;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * This class gather and manage statistics and report them in file
 * 
 * @author Omid
 * 
 */

public class StatManager implements Runnable
{

    private static Thread	    myThrd;

    private static Logger	    statLogger;
    private static Logger	    logger;
    private static Handler	   statFileHndl;

    private static Vector<Countable> countables = new Vector<Countable>();
    private int		      interval   = 10000;


    public StatManager()
    {
	myThrd = new Thread( this, "StatManager" );
	statLogger = Logger.getLogger( "StatisticsLogger" );
	logger = Logger.getLogger( this.getClass().getSimpleName() );
	statLogger.setLevel( Level.FINEST );
	setFile( "stat.log" );
	setFormatter( new StatFormatter() );
    }

    public static void addCountable( Countable cntb )
    {
	countables.add( cntb );
    }

    public static void setFile( String fileName )
    {
	try
	{
	    statFileHndl = new FileHandler( fileName );
	    statLogger.addHandler( statFileHndl );
	    statLogger.setUseParentHandlers( false );
	}
	catch( SecurityException e )
	{
	    logger.warning( "Creatig statistics file failed: " + e.getMessage() );
	}
	catch( IOException e )
	{
	    logger.warning( "Creatig statistics file failed: " + e.getMessage() );
	}
    }

    public static void setFormatter( Formatter frm )
    {
	statFileHndl.setFormatter( frm );
    }

    public static void start()
    {
	myThrd.start();
    }
    
    public static void log( String msg )
    {
	statLogger.info( msg );
    }

    public void run()
    {
	while( true )
	{
	    for( Countable countable : countables )
	    {
		Counter [] cntrs = countable.retrieveCounters();
		for( Counter counter : cntrs )
		{
		    processCounter( counter );
		}
	    }
	    try
	    {
		Thread.sleep( this.interval );
	    }
	    catch( InterruptedException e )
	    {
		logger.info( "Statistics interval sleep interrupted" );
	    }
	}
    }

    private void processCounter( Counter c )
    {
	statLogger.info( "Counter=" + c.getName() + ",Count=" + c.getNum() );
    }

}
